<template>
  <ProjectInfo
    ref="projectInfoRef"
    :preview="true"
    :sign="true"
    :sync="true"
    :syncContent="'从定性采样同步信息'"
    :signContent="'签字完成定性样品'"
    :projectId="`${route.query.projectId}`"
    :reportType="'NNNOCX'"
    @on-sync-header="onSyncHeader"
    @preview-file="previewFile"
    :needSignatureCheck="true"
    @signature="handleSignature"
  />
  <div>
    <div v-if="!sampleHandoverList.length" class="empty-tip"> 点击同步获取数据</div>
    <div v-for="(item, idx) in sampleHandoverList" :key="`${idx}-${refreshKey}`" class="record-item">
      <SampleHandoverRecord title="定性样品交接记录表" :form-data="item" @update="(val) => onRecordUpdate(val, idx)" />
    </div>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import SampleHandoverRecord from './SampleHandoverRecord.vue'
import { ProjectApi } from '@/api/dk/project'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import ProjectInfo from '@/views/project/list/ProjectInfo.vue'

const route = useRoute()
const router = useRouter()
const sampleHandoverList = ref<any[]>([])
const refreshKey = ref(0)
const projectInfoRef = ref()
defineOptions({ name: 'SampleHandoverIndex' })

/** 添加开始调查方法 */
const previewFile = () => {
  // 跳转到现场调查页面，并携带项目信息
  const { projectId, projectNo } = route.query
  router.push({
    path: '/previewFile',
    query: {
      projectId: projectId,
      projectNo: projectNo,
      operationType: 91
    }
  })
}

const handleSignature = () => {
  // 先进行数据校验
  if (signatureCheck()) {
    // 校验通过，显示签名弹窗
    if (projectInfoRef.value) {
      projectInfoRef.value.showSignatureDialog()
    }
  }
  // 校验不通过时，不显示弹窗，错误信息已在 signatureCheck 中提示
}

// 校验签名前的数据完整性
const signatureCheck = (): boolean => {
  // 校验是否有数据
  if (!sampleHandoverList.value || sampleHandoverList.value.length === 0) {
    ElMessage.error('请先同步数据')
    return false
  }

  // 遍历所有记录
  for (let recordIndex = 0; recordIndex < sampleHandoverList.value.length; recordIndex++) {
    const record = sampleHandoverList.value[recordIndex]

    // 检查记录是否有 table 数组
    if (!record.table || !Array.isArray(record.table) || record.table.length === 0) {
      continue
    }

    // 遍历表格中的每一行
    for (let rowIndex = 0; rowIndex < record.table.length; rowIndex++) {
      const row = record.table[rowIndex]
      const inspectionItems = row.inspectionItems || ''

      // 检查检测项目是否包含"有机"
      if (inspectionItems.includes('有机')) {
        // 如果包含"有机"，检查图片是否已上传
        const image = row.image
        if (!image || image.trim() === '') {
          ElMessage.error(`第${rowIndex + 1}行的检测项目务必上传图片`)
          return false
        }
      }
    }
  }

  return true
}

const onSyncHeader = async () => {
  // 显示确认弹窗
  try {
    await ElMessageBox.confirm('同步后本地数据将被清空，确认是否继续同步？', '同步确认', {
      confirmButtonText: '确认同步',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch {
    // 用户取消同步
    return
  }

  // 先清空数据，确保旧数据（包括图片）完全清除
  sampleHandoverList.value = []

  const projectId = route.query.projectId as string
  const result = await ProjectApi.getDefaultQualitativeHandoverRecord(Number(projectId))
  console.log('同步结果:', JSON.stringify(result))

  // 确保数据完全清空后再赋值新数据
  sampleHandoverList.value = result || []
  ElMessage.success('从方案同步成功')

  // 新增：同步后手动触发 onRecordUpdate
  await updateUnknownAnalysisHandoverRecord()

  // 重新获取最新数据以确保数据一致性
  await initData()

  // 强制重新渲染组件，清除可能的图片残留
  refreshKey.value++
}

const onRecordUpdate = (val, idx) => {
  sampleHandoverList.value[idx] = val
  console.log('form updated:', JSON.stringify(val))
  updateUnknownAnalysisHandoverRecord()
}

const updateUnknownAnalysisHandoverRecord = async() => {
  await ProjectApi.updateUnknownAnalysisHandoverRecord({
    projectId: route.query.projectId,
    sampleHandoverList: sampleHandoverList.value
  })
}

const initData =async () => {
  const projectId = route.query.projectId as string
  const { sampleHandoverList:sampleHandovers } = await ProjectApi.getUnknownAnalysisHandoverRecord(Number(projectId))
  console.log('数据', JSON.stringify(sampleHandovers))
  sampleHandoverList.value = sampleHandovers || []
}

onMounted(async () => {
  await initData()
})
</script>

<style lang="scss" scoped>
.top {
  padding-bottom: 20px;

  .top-btns {
    display: flex;
    justify-content: flex-end;
  }
}

.empty-tip {
  text-align: center;
  color: #bfbfbf;
  margin: 40px 0;
}
</style>
